import django_filters
from django.db.models import Q
from main.filters import NumberInFilter
from main.models import Client
from main.permissions import DjangoModelFullPermissions
from rest_framework import filters, serializers, viewsets


class ClientSerializer(serializers.ModelSerializer):
    requests = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True, required=False
    )
    orders = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True, required=False
    )
    contracts = serializers.PrimaryKeyRelatedField(
        many=True, read_only=True, required=False
    )

    class Meta:
        model = Client
        fields = (
            "id",
            "first_name",
            "last_name",
            "phone_number",
            "email",
            "note",
            "created_on",
            "updated_on",
            "requests",
            "orders",
            "contracts",
        )


class ClientFilter(django_filters.FilterSet):
    full_name = django_filters.CharFilter(method="_full_name_filter")
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Client
        fields = ("id", "first_name", "last_name")

    def _full_name_filter(self, queryset, name, value):
        return queryset.filter(
            Q(first_name__icontains=value) | Q(last_name__icontains=value)
        )


class ClientViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Clients to be viewed.
    """

    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    permission_classes = (DjangoModelFullPermissions,)
    filter_backends = [
        filters.SearchFilter,
        django_filters.rest_framework.DjangoFilterBackend,
    ]
    filterset_class = ClientFilter
    #
    # def list(self, request, *args, **kwargs):
    #     return
